﻿// Copyright (c) egmkang wang. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace XServer.Grains
{
    using System;
    using System.Collections.Concurrent;
    using System.Threading.Tasks;
    using XServer.GrainInterfaces;
    using XServer.SDK;
   

    /// <summary>
    /// 批量获取UID的信息
    /// 包含UID和BatchCount
    /// 封装了获取UID的函数
    /// </summary>
    public sealed class UniqueIDInfo
    {
        public static readonly int BatchCount = 512 * 10;

        public UniqueIDInfo(string uidName, IUniqueIDGrain grain)
        {
            this.uidName = uidName;
            this.grain = grain;
        }

        public string uidName;
        public AtomicInt64 uid;
        public AtomicInt64 uidEnd;
        public IUniqueIDGrain grain;
    }

    public static class UniqueIDHelper
    {
        public static void InitUniqueID(UniqueIDInfo info)
        {
            if (dict.ContainsKey(info.uidName)) return;

            try
            {
                info.uid = new AtomicInt64(0);
                info.uidEnd = new AtomicInt64(0);
                dict.TryAdd(info.uidName, info);
            }
            catch(Exception e)
            {
                LoggerProvider.Logger.Error("UniqueIDHelper.InitUniqueID, Message:{0}", e.Message);
            }
        }

        public async static Task<long> GetNewID(string uidName)
        {
            var info = dict[uidName];
            if (info.uid >= info.uidEnd)
            {
                var uid = await info.grain.GetBatchNewID(UniqueIDInfo.BatchCount);
                info.uid.Store(uid);
                info.uidEnd.Store(uid + UniqueIDInfo.BatchCount);
            }
            return info.uid++;
        }

        static ConcurrentDictionary<string, UniqueIDInfo> dict = new ConcurrentDictionary<string, UniqueIDInfo>();
    }
}
